package com.zh.mycommon.value;

import java.beans.Introspector;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.function.Function;

@FunctionalInterface
public interface TypeFunction<T, R> extends Serializable, Function<T, R> {

    class Inner {
        private Inner() {
        }

        static String getLambdaColumnName(Serializable lambda) {
            try {
                Method method = lambda.getClass().getDeclaredMethod("writeReplace");
                method.setAccessible(true);
                SerializedLambda serializedLambda = (SerializedLambda) method.invoke(lambda);
                String getter = serializedLambda.getImplMethodName();
                return Introspector.decapitalize(getter.replaceFirst("^(get|is|set)", ""));
            } catch (ReflectiveOperationException e) {
                throw new IllegalCallerException(e);
            }
        }
    }

    /**
     * 获取字段名
     * @param get get方法
     * @return field name
     * @param <T> T
     * @param <R> R
     */
    static <T, R> String fieldName(TypeFunction<T, R> get) {
        return Inner.getLambdaColumnName(get);
    }
}